<?php

namespace app\modules\backend\controllers;

use Yii;
use app\tools\Re;
use app\models\Base;
use app\models\Banner;

class BannerController extends BaseController
{
  /**
   * @param string $type
   * @return array
   */
  public function actionList(){
    $title = Yii::$app->request->post('title', '');
    $page = Yii::$app->request->post('page', 0);
    $page_size = Yii::$app->request->post('page_size', 20);
    $query = Banner::find()->where(['status' => [0,1]]);
    if (!empty($title)) {
      $query->andWhere(['like', 'title', $title]);
    }
    $list = $query->orderBy('sort desc, created_at desc')->limit($page_size)->offset($page_size*$page)->all();
    $data = [];
    if ($list) {
      foreach($list as $v) {
        $data[] = [
          'id' => $v->id,
          'title' => $v->title,
          'cover' => $v->cover,
          'good_id' => $v->good_id,
          'good_name' => $v->good_id ? $v->good->name : '',
          'sort' => $v->sort,
          'target_type' => $v->target_type,
          'status' => $v->status,
          'status_name' => $v->status ? '启用' : '禁用',
          'created_time' => date('Y-m-d H:i:s', $v->created_at)
        ];
      }
    }
    return Re::data([
      'data' => $data,
      'totalPage' => $query->count(),
      'currentPage' => $page,
      'perPage' => $page_size
    ]);
  }

  public function actionEdit(){
    $id = Yii::$app->request->post('id', 0);
    $post = Yii::$app->request->post();
    //var_dump($post);die;
    $keys = array_keys($post);
    $first_key = $keys[0];
    if (!$first_key) {
      return;
    }
    return $this->edit(Banner::class, $id, $post);
  }

  public function actionChangeStatus(){
    $id = Yii::$app->request->post('id', 0);
    $status = Yii::$app->request->post('status', 0);
    $model = Banner::findOne($id);
    if (empty($model)) {
      return Re::data(null, '轮播图信息读取失败', Re::ERROR);
    }
    $model->status = $status;
    if (!$model->save()) {
      return Re::data(null, '操作失败', Re::ERROR);
    }
    return Re::data();
  }
}
